<template>
  <div ref="containerRef" class="relative overflow-hidden" :class="containerClass">
    <!-- 占位符 -->
    <div
      v-if="!isLoaded && !hasError && !isIntersecting"
      class="absolute inset-0 bg-background-800 animate-pulse flex items-center justify-center"
      :class="placeholderClass"
    >
      <div class="text-text-muted text-sm">等待加载...</div>
    </div>

    <!-- 加载中状态 -->
    <div
      v-if="isIntersecting && !isLoaded && !hasError"
      class="absolute inset-0 bg-background-800 animate-pulse flex items-center justify-center"
      :class="placeholderClass"
    >
      <div class="text-text-muted text-sm">加载中...</div>
    </div>

    <!-- 错误状态 -->
    <div
      v-if="hasError"
      class="absolute inset-0 bg-background-800 flex items-center justify-center"
      :class="placeholderClass"
    >
      <div class="text-text-muted text-sm">加载失败</div>
    </div>

    <!-- 实际图片 -->
    <img
      v-if="isIntersecting"
      :src="src"
      :alt="alt"
      :class="imageClass"
      @load="onLoad"
      @error="onError"
      loading="lazy"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted, watch } from 'vue'

  interface Props {
    src: string
    alt?: string
    containerClass?: string
    imageClass?: string
    placeholderClass?: string
    threshold?: number
  }

  const props = withDefaults(defineProps<Props>(), {
    alt: '',
    containerClass: '',
    imageClass: 'w-full h-full object-cover',
    placeholderClass: '',
    threshold: 0.1,
  })

  const isLoaded = ref(false)
  const hasError = ref(false)
  const isIntersecting = ref(false)
  const containerRef = ref<HTMLElement>()
  let observer: IntersectionObserver | null = null

  const onLoad = () => {
    console.log('LazyImage: 图片加载成功', props.src)
    isLoaded.value = true
    hasError.value = false
  }

  const onError = () => {
    console.log('LazyImage: 图片加载失败', props.src)
    hasError.value = true
    isLoaded.value = false
  }

  // 监听 src 变化，重置状态
  watch(
    () => props.src,
    () => {
      isLoaded.value = false
      hasError.value = false
      isIntersecting.value = false
    },
  )

  onMounted(() => {
    // 创建 Intersection Observer
    observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            console.log('LazyImage: 进入视口，开始加载', props.src)
            isIntersecting.value = true
            observer?.disconnect()
          }
        })
      },
      {
        threshold: props.threshold,
        rootMargin: '50px',
      },
    )

    // 开始观察当前组件的容器
    if (containerRef.value) {
      observer.observe(containerRef.value)
    }
  })

  onUnmounted(() => {
    observer?.disconnect()
  })
</script>

<style scoped>
  /* 移除不需要的样式 */
</style>
